import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, setToken, setCountdown } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: 'http://localhost:80', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 100000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    if (response.data instanceof Blob) return response.data
    if (response.headers['refresh-token'] || response.headers['Refresh-Token']) {
      let token = response.headers['refresh-token'] ? response.headers['refresh-token'] : response.headers['Refresh-Token']
      let time = response.headers['refresh-timestamp'] ? response.headers['refresh-timestamp'] : response.headers['Refresh-Timestamp']
      setToken(token)
      setCountdown(time)
    }
    const res = response.data
    if (res.status !== '2000') {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
      if (res.status === '1008') {
        store.dispatch('user/resetToken').then(() => {
          // 跳转到首页
          router.push({ path: '/home' })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
      showClose: true
    })
    return Promise.reject(error)
  }
)

export default service
